<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
  <title>管理员管理</title>
  <link rel="icon" href="/static/images/favicon.ico" type="image/ico">
  <meta name="keywords" content="LightYear,光年,后台模板,后台管理系统,光年HTML模板">
  <meta name="description" content="LightYear是一个基于Bootstrap v3.3.7的后台管理系统的HTML模板。">
  <meta name="author" content="yinqi">
  <link href="/static/css/bootstrap.min.css" rel="stylesheet">
  <link href="/static/css/materialdesignicons.min.css" rel="stylesheet">
  <link href="/static/css/animate.css" rel="stylesheet">
  <link href="/static/css/style.min.css" rel="stylesheet">
  <link href="/static/js/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">
  <!--对话框-->
  <link rel="stylesheet" href="/static/js/jconfirm/jquery-confirm.min.css">
</head>

<body>
<div class="container-fluid p-t-15">

  <div class="row">
    <div class="col-lg-12">
      <div class="card">
        <div class="card-header"><h4>管理员管理</h4></div>
        <div class="card-body">

          <div id="toolbar" class="toolbar-btn-action">
            <button id="btn_add" type="button" class="btn btn-primary m-r-5">
              <span class="mdi mdi-plus" aria-hidden="true"></span>新增
            </button>
            <button id="btn_enable" type="button" class="btn btn-success m-r-5">
              <span class="mdi mdi-check" aria-hidden="true"></span>启用
            </button>
            <button id="btn_disable" type="button" class="btn btn-warning m-r-5">
              <span class="mdi mdi-block-helper" aria-hidden="true"></span>禁用
            </button>
            <button id="btn_delete" type="button" class="btn btn-danger">
              <span class="mdi mdi-window-close" aria-hidden="true"></span>删除
            </button>
          </div>
          <table id="table"></table>

        </div>
      </div>
    </div>
  </div>
</div>

<!-- 添加管理员的modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">添加管理员</h4>
      </div>
      <div class="modal-body">
        <form class="form-horizontal">
          <div class="form-group">
            <label for="username" class="col-sm-2 control-label">姓名</label>
            <div class="col-sm-10">
              <input type="text" class="form-control" id="username" placeholder="管理员姓名" required>
              <span class="help-block"></span>
            </div>
          </div>
          <div class="form-group">
            <label for="password" class="col-sm-2 control-label">初始密码</label>
            <div class="col-sm-10">
              <input type="text" class="form-control" id="password" placeholder="初始密码" required value="123456">
            </div>
          </div>
          <div class="form-group">
            <label class="col-sm-2 control-label">级别</label>
            <div class="col-sm-10">
              <label class="radio-inline">
                <input type="radio" name="level" value="1" checked> 普通管理员
              </label>
              <label class="radio-inline">
                <input type="radio" name="level" value="0"> 超级管理员
              </label>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            <button type="submit" class="btn btn-primary" id="submit_btn">提交</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<script type="text/javascript" src="/static/js/jquery.min.js"></script>
<script type="text/javascript" src="/static/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/static/js/perfect-scrollbar.min.js"></script>
<script type="text/javascript" src="/static/js/bootstrap-table/bootstrap-table.min.js"></script>
<script type="text/javascript" src="/static/js/bootstrap-table/bootstrap-table-zh-CN.min.js"></script>

<!--行内编辑插件-->
<link href="/static/js/x-editable/1.5.1/bootstrap3-editable/css/bootstrap-editable.min.css" rel="stylesheet">
<script type="text/javascript"
        src="/static/js/x-editable/1.5.1/bootstrap3-editable/js/bootstrap-editable.min.js"></script>
<script type="text/javascript"
        src="/static/js/bootstrap-table/extensions/editable/bootstrap-table-editable.min.js"></script>
<!--对话框-->
<script src="/static/js/jconfirm/jquery-confirm.min.js"></script>
<script type="text/javascript" src="/static/js/lightyear.js"></script>
<script src="/static/js/bootstrap-notify.min.js"></script>
<script type="text/javascript" src="/static/js/main.min.js"></script>
<script src="/static/js/mycommons.js"></script>
<script type="text/javascript">
  $('#table').bootstrapTable({
    classes: 'table table-bordered table-hover table-striped',
    url: '/admins',
    method: 'get',
    dataType: 'json',
    uniqueId: 'id',
    idField: 'id',             // 每行的唯一标识字段
    toolbar: '#toolbar',       // 工具按钮容器
    showColumns: true,         // 是否显示所有的列
    showRefresh: true,         // 是否显示刷新按钮

    pagination: true,                    // 是否显示分页
    paginationLoop: false,                // 禁用分页循环
    paginationSuccessivelySize: 5,        // 连续的最大连续页数
    paginationPagesBySide: 1,            // 当前页面每侧（右、左）的页数
    sortName: 'id',
    sortOrder: "asc",                    // 排序方式
    queryParams: function (params) {
      let param = {
        limit: params.limit,         // 每页数据量
        page: (params.offset / params.limit) + 1, //查询页码
        search: params.search,        // 搜索内容
        sort: params.sort,            // 排序列
        order: params.order           // 排序方式
      };
      return param;
    },                                   // 传递参数
    sidePagination: "server",            // 分页方式：client客户端分页，server服务端分页
    pageNumber: 1,                       // 初始化加载第一页，默认第一页
    pageSize: 5,                        // 每页的记录行数
    pageList: [5, 6, 7, 8, 9, 10],         // 可供选择的每页的行数
    search: true,                      // 是否显示表格搜索，此搜索是客户端搜索
    searchHighlight: true,          // 搜索高亮
    searchOnEnterKey: true,         //按 Enter 键搜索

    columns: [{
      checkbox: true    // 是否显示复选框
    }, {
      field: 'id',
      title: 'ID',
      sortable: true    // 是否排序
    }, {
      field: 'pic',
      title: '头像',
      formatter: function (value, row, index) {
        return '<img class="img-avatar img-avatar-48 m-r-10" src="/static/admin_pic/' + value + '" alt=""/>'
      }
    }, {
      field: 'name',
      title: '管理员名称',
    }, {
      field: 'level',
      title: '等级',
      sortable: true,
      formatter: function (value, row, index) {
        let p = '-'
        if (value === 0) {
          p = '<p class="text-danger">超级管理员</p>'
        } else if (value === 1) {
          p = '<p class="text-muted">普通管理员</p>'
        }
        return p
      }
    }, {
      field: 'createTime',
      title: '创建时间',
      formatter: formatTimeStr
    }, {
      field: 'lastEditTime',
      title: '最近编辑时间',
      formatter: formatTimeStr
    }, {
      field: 'status',
      title: '状态',
      sortable: true,
      editable: {
        type: 'select',
        title: "状态",
        pk: 1,
        source: [
          {value: 0, text: '禁用'},
          {value: 1, text: '正常'}
        ],
        noeditFormatter: function (value, row, index) {
          let result;
          if (value == '0' || value == '禁用') {
            result = {filed: "status", value: "禁用", class: "label label-danger"};
          } else if (value == '1' || value == '正常') {
            result = {filed: "status", value: "正常", class: "label label-success"};
          }

          return result; // 这里对bootstrap-table-editable.min.js做了一些修改，让其能接收class
        },
      }
    }, {
      field: 'operate',
      title: '操作',
      formatter: btnGroup,  // 自定义方法
      events: {
        'click .edit-btn': function (event, value, row, index) {
          editUser(row.id);
        },
        'click .del-btn': function (event, value, row, index) {
          tb_deleteOne(row.id, '/admin')
        },
        'click .show-btn': function (event, value, row, index) {
          showUser(row);
        }
      }
    }],
    onEditableSave: function (field, row, oldValue, $el) {
      $.ajax({
        type: "PUT",
        url: "/admin/" + row.id,
        data: {status: row.status},
        dataType: 'json',
        success: function (res) {
          if (res.flag) {
            msgNotify(res.msg, 'success', 1500)
            $('#table').bootstrapTable('updateRow', {index: row.id, row: row});
          } else {
            msgNotify(res.msg, 'danger', 1500)
          }
        },
        error: function () {
          msgNotify('修改失败，请稍后再试', 'danger', 1500)
        }
      });
    },
    onLoadSuccess: function (data) {
      $("[data-toggle='tooltip']").tooltip();
    }
  });


  // 操作方法 - 编辑
  function editUser() {
  }

  // 操作方法 - 查看
  function showUser() {
  }

  /*
  批量删除
 */
  tb_deleteBatch("/admin")

  /*
批量启用
 */
  $("#btn_enable").click(function () {
    changeStatusBatch(1, '/admin')
  })

  /*
  批量禁用
   */
  $("#btn_disable").click(function () {
    changeStatusBatch(0, '/admin')
  })

  /*
  点击新增按钮弹出模态框
   */
  $("#btn_add").click(function () {
    //弹出模态框
    $("#myModal").modal({
      backdrop: "static"
    })
  })

  /*
  新增管理员
   */
  $("#submit_btn").click(function (e) {
    let name = $.trim($("#username").val())
    let pwd = $.trim($("#password").val())
    let level = $("input[type='radio']").val()

    if (name !== '' && name.length !== 0 && /^[\u4e00-\u9fa5]{2,5}$/.test(name)) {
      show_verify_info('#username', 'success', '')
    } else {
      show_verify_info('#username', 'error', '请输入2-5位中文')
      return false
    }

    if ($(this).attr("admin-exist") === "true") {
      return false
    }

    e.preventDefault()
    $("#myModal").modal('hide')

    $.post('/admin', {name:name, password: pwd, level: level}, function (res) {
      if (res.flag) {
        load(1)
        msgNotify(res.msg, 'success', 1500)
      } else {
        msgNotify(res.msg, 'danger', 1500)
      }
    })
  })

  //查询管理员姓名是否已存在
  $(document).on("input propertychange", "#username", function () {
    let name = $.trim($(this).val())
    $.get('/admin', {name:name}, function (res) {
      if (res.flag) {
        show_verify_info(this, "success", "")
        $("#submit_btn").attr("admin-exist", "false")
      } else {
        show_verify_info(this, 'error', res.msg)
        $("#submit_btn").attr("admin-exist", "true")
      }
    })
  })

  /*
显示校验信息
 */
  function show_verify_info(item, status, msg) {
    $(item).parent().removeClass("has-success has-error")
    if ("success" === status) {
      $(item).parent().addClass("has-success")
      $(item).next("span").text("")
    } else if ("error" === status) {
      $(item).parent().addClass("has-error")
      $(item).next("span").text(msg)
    }
  }
</script>
</body>
</html>